<template>
	<div class="realtime-monitor">
		<el-card class="statistics-card">
			<template #header>
				<div class="card-header">
					<span>实时统计</span>
				</div>
			</template>
			<el-row :gutter="20">
				<el-col :span="6" v-for="(stat, index) in statistics" :key="index">
					<el-card class="stat-item" shadow="hover">
						<div class="stat-value">{{ stat.value }}</div>
						<div class="stat-label">{{ stat.label }}</div>
					</el-card>
				</el-col>
			</el-row>
		</el-card>

		<el-card class="control-card">
			<template #header>
				<div class="card-header">
					<span>任务控制</span>
				</div>
			</template>
			<div class="control-buttons">
				<el-button type="primary" @click="startTask" :disabled="isTaskRunning">
					<el-icon><VideoPlay /></el-icon>
					开始任务
				</el-button>
				<el-button type="danger" @click="stopTask" :disabled="!isTaskRunning">
					<el-icon><VideoPause /></el-icon>
					停止任务
				</el-button>
				<el-button @click="refreshData">
					<el-icon><Refresh /></el-icon>
					刷新数据
				</el-button>
			</div>
			<div class="task-status">
				<el-tag :type="isTaskRunning ? 'success' : 'info'">
					{{ isTaskRunning ? '任务运行中' : '任务已停止' }}
				</el-tag>
			</div>
		</el-card>

		<el-card class="results-card">
			<template #header>
				<div class="card-header">
					<span>实时校验结果</span>
				</div>
			</template>
			<div class="results-container">
				<div v-if="validationResults.length === 0" class="no-data">
					暂无数据
				</div>
				<div v-else>
					<DocumentItem
						v-for="(item, index) in validationResults"
						:key="index"
						:document="item"
						@delete="handleDelete"
					/>
				</div>
			</div>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { VideoPlay, VideoPause, Refresh } from '@element-plus/icons-vue';
import { useHistoryDataApi } from '/@/api/historyData';
import DocumentItem from '/@/views/monitor/components/DocumentItem.vue';

// 定义响应式数据
const statistics = ref([
	{ label: '今日处理', value: 0 },
	{ label: '今日成功', value: 0 },
	{ label: '今日失败', value: 0 },
	{ label: '待处理', value: 0 }
]);

const isTaskRunning = ref(false);
const validationResults = ref([]);
const historyDataApi = useHistoryDataApi();

// WebSocket连接
// 暂时不使用 WebSocket
// let websocket: WebSocket | null = null;

// 获取统计数据
const fetchStatistics = async () => {
	try {
		const response = await historyDataApi.getStatistics();
		if (response.data) {
			statistics.value = [
				{ label: '今日处理', value: response.data.today_processed || 0 },
				{ label: '今日成功', value: response.data.today_success || 0 },
				{ label: '今日失败', value: response.data.today_failed || 0 },
				{ label: '待处理', value: response.data.pending || 0 }
			];
		}
	} catch (error) {
		console.error('获取统计数据失败:', error);
		ElMessage.error('获取统计数据失败');
	}
};

// 开始任务
const startTask = async () => {
	try {
		// 这里应该调用开始任务的API
		// 暂时使用模拟数据
		isTaskRunning.value = true;
		ElMessage.success('任务已启动');
		
		// 连接WebSocket
		connectWebSocket();
	} catch (error) {
		console.error('启动任务失败:', error);
		ElMessage.error('启动任务失败');
	}
};

// 停止任务
const stopTask = async () => {
	try {
		// 这里应该调用停止任务的API
		// 暂时使用模拟数据
		isTaskRunning.value = false;
		ElMessage.success('任务已停止');
		
		// 断开WebSocket
		// 暂时不使用 WebSocket
		// if (websocket) {
		// 	websocket.close();
		// 	websocket = null;
		// }
	} catch (error) {
		console.error('停止任务失败:', error);
		ElMessage.error('停止任务失败');
	}
};

// 刷新数据
const refreshData = async () => {
	await fetchStatistics();
	ElMessage.success('数据已刷新');
};

// 处理删除
const handleDelete = (id: string) => {
	validationResults.value = validationResults.value.filter(item => item.id !== id);
	ElMessage.success('已删除');
};

// 连接WebSocket
// 暂时不使用 WebSocket
const connectWebSocket = () => {
	// 暂时不使用 WebSocket
	// if (websocket) {
	// 	websocket.close();
	// }
	
	// 创建WebSocket连接
	// 注意：这里需要根据实际的WebSocket服务器地址进行调整
	// websocket = new WebSocket('ws://localhost:8000/ws/validation/');
	
	// websocket.onopen = () => {
	// 	console.log('WebSocket连接已建立');
	// };
	
	// websocket.onmessage = (event) => {
	// 	try {
	// 		const data = JSON.parse(event.data);
	// 		if (data.type === 'validation_result') {
	// 			// 将新结果添加到数组开头
	// 			validationResults.value.unshift(data.result);
	// 			// 限制结果数量，避免过多
	// 			if (validationResults.value.length > 50) {
	// 				validationResults.value = validationResults.value.slice(0, 50);
	// 			}
	// 		}
	// 	} catch (error) {
	// 		console.error('解析WebSocket消息失败:', error);
	// 	}
	// };
	
	// websocket.onerror = (error) => {
	// 	console.error('WebSocket错误:', error);
	// 	ElMessage.error('WebSocket连接错误');
	// };
	
	// websocket.onclose = () => {
	// 	console.log('WebSocket连接已关闭');
	// 	isTaskRunning.value = false;
	// };
	console.log('WebSocket功能已禁用');
};

// 组件挂载时获取统计数据
onMounted(() => {
	fetchStatistics();
});

// 组件卸载时关闭WebSocket
// 暂时不使用 WebSocket
// onUnmounted(() => {
// 	if (websocket) {
// 		websocket.close();
// 	}
// });
</script>

<style scoped>
.realtime-monitor {
	padding: 20px;
}

.statistics-card,
.control-card,
.results-card {
	margin-bottom: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-weight: bold;
}

.stat-item {
	text-align: center;
	padding: 15px;
}

.stat-value {
	font-size: 24px;
	font-weight: bold;
	color: #409EFF;
	margin-bottom: 5px;
}

.stat-label {
	font-size: 14px;
	color: #909399;
}

.control-buttons {
	display: flex;
	gap: 10px;
	margin-bottom: 15px;
}

.task-status {
	display: flex;
	align-items: center;
}

.results-container {
	max-height: 500px;
	overflow-y: auto;
}

.no-data {
	text-align: center;
	padding: 20px;
	color: #909399;
}
</style>